package com.hc.comm.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.hc.comm.model.ResultMeta;

public class MyUtils {

	
	
	public static String getFormatTimeString() {
		Date date = new Date();

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		return df.format(date);
	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}

		return true;
	}



	public static String getFileName(String path, String strUrl) {
		if (strUrl == null) {
			return null;
		}

		if (strUrl.indexOf("http") != -1) {
			int start = strUrl.lastIndexOf("/");
			int end = strUrl.length();

			if (start != -1 && end != -1) {
				return path + strUrl.substring(start + 1, end);
			} else {
				return null;
			}
		} else {
			int start = strUrl.lastIndexOf("/");
			int end = strUrl.length();
			if (start == -1) {
				start = 0;
			}

			return path + strUrl.substring(start, end);
		}

	}

	public static String getFileFormat(String pathandname) {
		if (pathandname == null || pathandname.length() == 0) {
			return null;
		}

		int start = pathandname.lastIndexOf(".");
		if (start != -1) {
			return pathandname.substring(start + 1, pathandname.length());
		}

		return null;
	}

	public static StringBuffer getImageHost(HttpServletRequest request) {
		StringBuffer ctxPath = new StringBuffer();
		ctxPath.append(request.getSession().getServletContext()
				.getRealPath(File.separator));

		int start = ctxPath.indexOf("fe_mobile");
		if (start != -1) {
			ctxPath.delete(start, ctxPath.length());
		}

		ctxPath.append(File.separator + "FruitExpress" + File.separator);
		File dirPath = new File(ctxPath.toString());
		if (!dirPath.exists()) {
			dirPath.mkdir();
		}

		return ctxPath;
	}

	public static void deleteOldImage(HttpServletRequest request,
			JSONObject actionParam) {
		String oldImg = actionParam.getString("oldImg");
		deleteImages(request, oldImg);
	}

	public static void deleteImages(HttpServletRequest request, String fileName) {
		if (fileName != null && fileName.length() > 0) {
			StringBuffer ctxPath = getImageHost(request);
			String filePart[] = fileName.split("_");
			String landString = "";
			if (filePart != null && filePart.length > 0) {
				ctxPath.append(File.separator + filePart[0]).append(
						File.separator);
				if (filePart[0].equalsIgnoreCase("fruit.AddFruit")) {
					landString = "landscape";
				}
			}

			String delFileName = MyUtils.getFileName(ctxPath.toString(),
					fileName);
			MyLog.log("旧的图片：" + delFileName);
			if (delFileName != null) {
				File delFile = new File(delFileName);
				if (delFile != null) {
					delFile.delete();
				}
			}

			delFileName = MyUtils.getFileName(ctxPath.toString() + "150"
					+ File.separator, fileName);
			MyLog.log("旧的150图片：" + delFileName);
			if (delFileName != null) {
				File delFile = new File(delFileName);
				if (delFile != null) {
					delFile.delete();
				}
			}
			
			delFileName = MyUtils.getFileName(ctxPath.toString() + "portait"
					+ File.separator, fileName);
			MyLog.log("旧的portait图片：" + delFileName);
			if (delFileName != null) {
				File delFile = new File(delFileName);
				if (delFile != null) {
					delFile.delete();
				}
			}

			if (landString.length() > 0) {
				delFileName = MyUtils.getFileName(ctxPath.toString()
						+ landString + File.separator, fileName);
				if (delFileName != null) {
					File delFile = new File(delFileName);
					if (delFile != null) {
						delFile.delete();
					}
				}
			}
		}
	}

	public static String compress(String str) {
		if (str == null || str.length() == 0) {
			return str;
		}

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip;
		try {
			gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes());
			gzip.close();

			return out.toString("ISO-8859-1");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			MyLog.log("e = " + e);
		}

		return null;
	}

	// 解压缩
	public static String uncompress(String str) {
		if (str == null || str.length() == 0) {
			return str;
		}

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in;
		try {
			in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
			GZIPInputStream gunzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}

			// toString()使用平台默认编码，也可以显式的指定如toString(&quot;GBK&quot;)
			return out.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			MyLog.log("e = " + e);
		}

		return null;
	}

	public static boolean isFileExist(String strFile) {

		boolean bRet = false;
		if (strFile != null && strFile.length() > 0) {
			File file = new File(strFile);
			if (file != null && file.exists()) {
				bRet = true;
			}

		}

		return bRet;
	}

	public static long getFileSizes(File file) {
		long nRet = 0;
		if (file == null) {
			return nRet;
		}

		if (file.exists()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				nRet = fis.available();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return nRet;
	}

	public static String filterName(String name) {
		String retString = "";
		if (StringUtil.isEmpty(name)) {
			return retString;
		}

		// com.fe.comm.model.FruitModel
		int pos = name.lastIndexOf(".");
		if (pos > -1) {
			String model = name.substring(pos + 1);
			retString = model.substring(0, model.length() - 5) + "Entity";
		}

		return retString;
	}
	
	
	public static String saveMultipartFile(MultipartHttpServletRequest request, MultipartFile file, JSONObject actionParam, ResultMeta result, String type, String fileName) {
		
		//CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
			//	.getFile("image");
		File uploadFile = null;
		long userId = actionParam.getLongValue("uid");
		StringBuffer ctxPath = MyUtils.getImageHost(request);
		if (file != null) {
		
			String segment = type.toLowerCase();

			// 创建文件
			ctxPath.append(File.separator + segment).append(File.separator);
			File dirPath = new File(ctxPath.toString());
			if (!dirPath.exists()) {
				dirPath.mkdir();
			}

			if (StringUtil.isEmpty(fileName)) {
				String timeNow = "" + System.currentTimeMillis();
				fileName = segment + "_" + userId + "_" + timeNow + ".jpg";
			}
			
			String savePath = ctxPath + fileName;

			MyLog.log("uploadEx succ savePath = " + savePath + ", fileSize = " + file.getSize());
			uploadFile = new File(savePath);
			try {
				FileCopyUtils.copy(file.getBytes(), uploadFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (uploadFile != null) {

			deleteOldImage(request, actionParam);

			String newFile = ctxPath + File.separator + "150"
					+ File.separator;
			File dirPath = new File(newFile);
			if (!dirPath.exists()) {
				dirPath.mkdir();
			}

			newFile = newFile + fileName;
			//ImageHelper.makeThumbnail(uploadFile, newFile, 150, 150);
			ImageHelper.saveImageAsJpg(uploadFile, newFile, 150, 150);
			if (type.equalsIgnoreCase("fruit.AddFruit")) {
				String landFile = ctxPath + File.separator + "landscape"
						+ File.separator;
				File landPath = new File(landFile);
				if (!landPath.exists()) {
					landPath.mkdir();
				}

				landFile = landFile + fileName;
				//ImageHelper.cutAdjustCenterImage(uploadFile, landFile, 400, 200);
				ImageHelper.saveImageAsJpg(uploadFile, landFile, 400, 200);
				
				String portaitFile = ctxPath + File.separator + "portait"
						+ File.separator;
				File pFile = new File(portaitFile);
				if (!pFile.exists()) {
					pFile.mkdir();
				}

				portaitFile = portaitFile + fileName;
				//ImageHelper.cutAdjustCenterImage(uploadFile, portaitFile, 200, 300);
				ImageHelper.saveImageAsJpg(uploadFile, portaitFile, 200, 300);
			}
		}
		
		return fileName;
	}

	public static String multipartFileList(MultipartHttpServletRequest request,
			JSONObject actionParam, ResultMeta result, String type) {
		boolean isHaveData = ServletFileUpload.isMultipartContent(request);
		String fileName = null;
		if (isHaveData) {
			Map<String, MultipartFile> fileMap = request.getFileMap();

			
			for (Entry<String, MultipartFile> entry : fileMap.entrySet()) {
				fileName = entry.getKey();
				MultipartFile file = entry.getValue();
				saveMultipartFile(request, file, actionParam, result, type, fileName);
				MyLog.log("fileName = " + fileName);

			}

			/*FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {

				List items = upload.parseRequest(request);
				MyLog.log("multipartFileList items.size() =  " + items.size());
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) {
						// 普通文本信息处理
						String paramName = item.getFieldName();
						String paramValue = item.getString();
						MyLog.log(paramName + ":" + paramValue);
					} else {
						// 上传文件信息处理
						String fileName = item.getName();
						byte[] data = item.get();
						String filePath = request.getSession()
								.getServletContext().getRealPath("/files")
								+ "/" + fileName;
						MyLog.log("file : " + filePath);
						FileOutputStream fos = new FileOutputStream(filePath);
						fos.write(data);
						fos.close();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}*/

		}
		
		return fileName;
	}

	public static String uploadEx(HttpServletRequest request,
			JSONObject actionParam, ResultMeta result, String type)
			throws IOException {

		
		String fileName = "";
		
		if (actionParam.containsKey("Attachment")) {
			MultipartHttpServletRequest multipartRequest = null;
			if (request instanceof MultipartHttpServletRequest) {
				multipartRequest = (MultipartHttpServletRequest) request;
			} else {
				MultipartResolver resolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());

				multipartRequest = resolver.resolveMultipart(request);
			}

			fileName = multipartFileList(multipartRequest, actionParam, result, type);

			MyLog.log("uploadEx finish   ");
		}

		return fileName;
	}
	
	
}
